
import axios, { AxiosInstance, AxiosResponse,AxiosRequestConfig } from 'axios';

const request = axios.create({
  baseURL: '/api'
});

// 添加请求拦截器

request.interceptors.request.use(function (config) {
  let token= localStorage.getItem('TOKEN')
  if(token){
    config.headers['Authorization'] = token
  }

  return config;
}, function (error) {
  return Promise.reject(error);
});


// 添加响应拦截器

request.interceptors.response.use(function (response) {
  return response;
}, function (error) {
  return Promise.reject(error);
});

const http = {
  get<T>(url: string, config?: AxiosRequestConfig & { params?: any }): Promise<T> {
    return new Promise((resolve, reject) => {
      // 将 params 从 config 中提取，并合并到 axios 的 config.params
      const { params, ...restConfig } = config || {};
      request
        .get<T>(url, { params, ...restConfig }) // 正确传递两个参数
        .then((res: AxiosResponse<T>) => {
          resolve(res.data);
        })
        .catch(reject);
    });
  },
  post<T>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> {
    return new Promise((resolve, reject) => {
      request
        .post<T>(url, data, config)
        .then((res: AxiosResponse<T>) => {
          resolve(res.data);
        })
        .catch((error) => {
          reject(error);
        });
    });
  },
};

export default http;
